﻿using DevComponents.DotNetBar;
using Model;
using Model.Enum;
using MQTTTool.Page.Com;
using MQTTTool.Static;
using MQTTTool.Util;
using SerailDriver;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MQTTTool.Controls
{
    public partial class ComPage : UserControl
    {
        SerailDriverCla driver;

        public ComConfig config1 = new ComConfig();
        public MQConfig config = new MQConfig();
        bool loopsend;//是否使用循环发送
        bool issending = false;//是否正在循环发送
        bool waitresult = true;//是否等待结果再循环
        public SerailDriverCla serailDriver;
        public List<AutoMsgModel> models;//自动回发消息的集合
                                         //public event ComPage AddLog
        /// <summary>
        /// 判断是否有保存过该窗体，若保存了则从保存的拿config初始化，否则自己初始化。
        /// </summary>
        /// <param name="config"></param>
        public ComPage(ComConfig config1, List<AutoMsgModel> models, MQConfig config)
        {
           AutoMsgForm auto = new AutoMsgForm(models);
            InitializeComponent();
            this.config1 = config1;
            this.config = config;
            {
                InitData();

            }
        }
        /// <summary>
        /// 将当前的配置项，
        /// </summary>
        public void GetConfig()
        {
            throw new NotImplementedException();
        }

        private void InitData()
        {
            integerInput_starti.Value = config1.nowindex;
            richTextBoxEx2.Text = Encoding.UTF8.GetString(config1.SendMsg.ToArray(), 0, config1.SendMsg.Count);
            integerInput_stream.Value = config1.streamlength;
            integerInput_waittime.Value = config1.waittime;
            models = config1.models;
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="logstr"></param>
        public void AddLog(string logstr, LogEnum logtype)
        {
            try
            {

                logstr = DateTime.Now.ToLocalTime() + " " + logstr;
                if (InvokeRequired)
                {
                    this.Invoke(new ThreadStart(delegate
                    {
                        this.Log(logstr, logtype);

                    }));
                }
                else
                {
                    this.Log(logstr, logtype);
                }
            }
            catch (Exception)
            {
                this.richTextBoxEx1.Clear();
            }
        }

        private void Log(string logstr, LogEnum logtype)
        {
            switch (logtype)
            {
                case LogEnum.SendLog:
                    this.richTextBoxEx1.AppendTextColorful(logstr, Color.Blue);

                    break;
                case LogEnum.ReceverLog:

                    this.richTextBoxEx1.AppendTextColorful(logstr, Color.Green);
                    break;
                case LogEnum.ErrLog:
                    this.richTextBoxEx1.AppendTextColorful(logstr, Color.Red);
                    break;
                default:
                    this.richTextBoxEx1.AppendTextColorful(logstr, Color.Black);
                    break;
            }
        }

        public ComPage()
        {
            InitializeComponent();
            AddComName();
           // savea();
            BaseItem basex = new ButtonItem("xxx", "xxxx");
            textBoxDropDown1.DropDownItems.Add(basex);
            basex.Click += CancelItem;
        }

        private void AddComName()
        {
            string[] com = SerialPort.GetPortNames();
            this.comboBoxEx_Com.Items.Clear();
            foreach (var item in com)
            {
                this.comboBoxEx_Com.Items.Add(item);
            }
        }

        private void CancelItem(object sender, EventArgs e) 
        {
            BaseItem item = (BaseItem)sender;
            textBoxDropDown1.DropDownItems.Remove(item);
        }

        private void buttonX5_Click(object sender, EventArgs e)
        {
            string[] com = SerialPort.GetPortNames();
            this.comboBoxEx_Com.Items.Clear();
            foreach (var item in com)
            {
                this.comboBoxEx_Com.Items.Add(item);
            }
        }

        private void buttonX6_Click(object sender, EventArgs e)
        {
            try
            {
                if (driver != null)
                {
                    driver.Close();
                }
                driver = new SerailDriverCla(models, comboBoxEx_Com.Text, int.Parse(comboBoxEx_btv.Text));
            }
            catch (Exception)
            {


            }
        }
        Task main;
        public void buttonX1_Click(object sender, EventArgs e)
        {
              
            if (serailDriver == null)
            {
                AddLog("请打开串口！！", LogEnum.ErrLog);
                return;
            }
            if (main != null)
            {
                return;
            }
            try
            {
                main = Task.Run(() =>
                {
                    try
                    {
                        if (loopsend)
                        {
                            try
                            {
                                //循环发送逻辑
                                issending = true;
                                int value = integerInput_starti.Value;
                                int loop = integerInput_loopcount.Value; //循环次数
                                //int sta = integerInput_starti.Value; //起始下标
                                for (int i = 0; issending && i < loop; i++, integerInput_starti.Value++)
                                {
                                    string msg = "";
                                    this.Invoke(new ThreadStart(delegate
                                    {
                                        DateTime currentTime = DateTime.Now;
                                        int sec = currentTime.Millisecond;
                                        msg = richTextBoxEx2.Text;

                                        string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
                                        //msg = msg.Replace(textBoxX_time.Text, nowTime);

                                        string stream = GetStream(integerInput_stream.Value, i + value);
                                        msg = msg.Replace(textBoxX_loopstr.Text, stream);
                                        #region 此处区分16进制
                                        msg = msg.Replace(textBoxX_loopstr.Text, stream);
                                        #endregion

                                        
                                        DateTime currentTime1 = DateTime.Now;
                                        int sec1 = currentTime1.Millisecond;
                                        int sec2 = int.Parse(integerInput_waittime.Text);
                                        Console.WriteLine(sec);
                                        Console.WriteLine(sec1);
                                        if (sec - sec1 >= 500)
                                        {
                                            return;
                                        }
                                    }));

                                    if (waitresult)
                                    {
                                        
                                        serailDriver.SendAndWait(msg, integerInput_timeout.Value);
                                        serailDriver.SendDataString0A(msg); 
                                        AddLog("发送消息:" + msg , LogEnum.SendLog);
                                        
                                    }
                                    else
                                    {
                                        serailDriver.SendDataString0A(msg);
                                    }
                                    Thread.Sleep(integerInput_waittime.Value);
                                }

                            }
                            catch (Exception ex)
                            {
                                AddLog(ex.Message + ex.StackTrace, LogEnum.ErrLog);

                            }
                            finally
                            {
                                issending = false;
                            }
                        }
                        else
                        {


                            /*//普通发送逻辑


							  string msg = "";
								this.Invoke(new ThreadStart(delegate
								{
									msg = richTextBoxEx2.Text;
									string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
									//msg = msg.Replace(textBoxX_time.Text, nowTime);
									
									*//*msg = msg.Replace(textBoxX_loopstr.Text, stream);*//*

								}));

								
								
									serailDriver.SendDataString0A(msg);
							AddLog("发送消息:" + msg, LogEnum.SendLog);
							//收到了消息
							AddLog("收到消息:" + Encoding.UTF8.GetString(serailDriver.ReturmData.ToArray()), LogEnum.ReceverLog);
							AddLog("收到消息:" + BitConverter.ToString(serailDriver.ReturmData.ToArray(), 0, serailDriver.ReturmData.Count), LogEnum.ReceverLog);
							//打印字节
							//richTextBoxEx2.Text = "";
*/

                            //普通发送逻辑

                            string msg = "";
                            this.Invoke(new ThreadStart(delegate
                            {
                                msg = richTextBoxEx2.Text;
                                string nowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
                                // serailDriver.SendDataString0A(msg);


                            }));
                            try
                            {

                                bool result = serailDriver.SendDataString0A(msg);

                                if (result == true)
                                {
                                    DateTime currentTime = DateTime.Now;
                                    int sec = currentTime.Millisecond;
                                    AddLog("发送消息:" + msg, LogEnum.SendLog);
                                    /*while (true)
                                    {*/
                                    Console.WriteLine(serailDriver);
                                    //AddLog("收到消息:" + BitConverter.ToString(serailDriver.ReturmData.ToArray(), 0, serailDriver.ReturmData.Count), LogEnum.ReceverLog);
                                    //if (serailDriver.ReturmData.Count > 0)
                                    //  {
                                    //收到了消息
                                    //AddLog("收到消息:" + Encoding.UTF8.GetString(serailDriver.ReturmData.ToArray()), LogEnum.ReceverLog);
                                    // AddLog("收到消息:" + BitConverter.ToString(serailDriver.ReturmData.ToArray(), 0, serailDriver.ReturmData.Count), LogEnum.ReceverLog);
                                    //打印字节
                                    //richTextBoxEx2.Text = "";
                                    //}
                                    DateTime currentTime2 = DateTime.Now;
                                    int sec2 = currentTime2.Millisecond;
                                    /*  if (sec - sec2 >= 500)
                                      {
                                          return;

                                      }*/
                                    /*  }*/
                                    //AddLog("收到消息:" + result, LogEnum.ReceverLog);

                                }
                                else
                                {
                                    AddLog("发送失败，请重试！", LogEnum.ErrLog);
                                }

                            }
                            catch (Exception exc)
                            {

                            }



                        }

                    }
                    catch (Exception ex)
                    {
                        AddLog(ex.Message + ex.StackTrace, LogEnum.ErrLog);

                    }
                    finally
                    {
                        main = null;
                    }

                });
            }
            catch (Exception ex)
            {

                AddLog(ex.Message + ex.StackTrace, LogEnum.ErrLog);

            }
            finally
            {
                main = null;

            }

        }

        /// <summary>
        /// s生成流水码
        /// </summary>
        /// <param name="length">流水码长度</param>
        /// <param name="data">数据位</param>
        /// <returns></returns>
        private string GetStream(int length, int data)
        {
            string stream = data + "";
            int len = stream.Length;
            for (int j = 0; j < length - len; j++)
            {
                stream = "0" + stream;
            }
            return stream;
        }


        private void checkBoxX_loop_CheckedChanged(object sender, EventArgs e)
        {
            loopsend = this.checkBoxX_loop.Checked;
        }

        private void switchButton1_ValueChanged(object sender, EventArgs e)
        {
           
            String comboBoxExcg = comboBoxEx_Com.Text; //串口
            int comboBoxExbtl = Convert.ToInt32(comboBoxEx_btv.Text);//波特率
            if (switchButton1.Value)
            {
                //打开

                serailDriver = new SerailDriverCla(models, comboBoxExcg, comboBoxExbtl);
                serailDriver.page += AddLog;
                //serailDriver.page1 += savea;
                serailDriver.Open();
            }
            else
            {
                serailDriver.Close();
            }
        }
        //存储16进制
        private string txt = "";
        private void checkBoxX_16_CheckedChanged(object sender, EventArgs e)
        { 
            //转换成16进制格式
            //bool checkBoxX_16= checkBoxX_16.

            bool checkBoxX_16 = this.checkBoxX_16.Checked;
          
            if (checkBoxX_16.Equals(true))
            {
                string rich = richTextBoxEx2.Text;
          

                System.Text.Encoding chs = System.Text.Encoding.UTF8;//GetEncoding("GB2312");
                 
                byte[] bytes = chs.GetBytes(rich);

                string msg = "";

                for (int i = 0; i < bytes.Length; i++)
                {
                    msg += (string.Format("{0:X}", bytes[i])+" ");
                }

                richTextBoxEx2.Text = msg;
                txt = msg;
            }
            else
            {
                /*************** 将 16进制字符串 解码成 字符串 ***************/
              
                string rich = richTextBoxEx2.Text;
                string msg ="";
                
                // 需要将 hex 转换成 byte 数组。
                List<Object> bytes = rich.Split(' ').Select<string, Object>(text =>
                {
                    try
                    {
                        return Convert.ToByte(text, 16);

                    }
                    catch (Exception)
                    {

                        return "";
                    }
                }).ToList<Object>();
                bytes.RemoveAll(item => item == "");
                byte[] blist = bytes.Select<object, byte>(item =>
                {
                    return (byte)item;

                }).ToArray();
                // 获得 GB2312，Chinese Simplified。
                Encoding chs = System.Text.Encoding.UTF8;//GetEncoding("GB2312");
                msg=chs.GetString(blist);
                richTextBoxEx2.Text = msg;

            }

        }

     /*   public static string DecodeHexadecimalToStr(string strDecode)
        {
            string result = string.Empty;

            byte[] arrByte = new byte[strDecode.Length / 2];
            int index = 0;
            for (int i = 0; i < strDecode.Length; i += 2)
            {
                arrByte[index++] = Convert.ToByte(strDecode  .Substring(i, 2), 16);        //Convert.ToByte(string,16)把十六进制string转化成byte 
            }
            result = System.Text.Encoding.UTF8.GetString(arrByte);

            return result;
        }*/

        private void buttonX2_Click(object sender, EventArgs e)
        {
            AutoMsgForm auto = new AutoMsgForm(models);
            DialogResult dialogr = auto.ShowDialog();
            if (dialogr == DialogResult.OK)
            {
                //若保存了，则用保存过后的model替换掉当前model
                models = auto.GetModels();
                serailDriver.modelsa(models);
            }

        }
       /* public void savea()
        {
            AutoMsgForm auto = new AutoMsgForm(models);
            DialogResult dialogr = auto.ShowDialog();
            if (dialogr == DialogResult.OK)
            {
                //若保存了，则用保存过后的model替换掉当前model
                models = auto.GetModels();
            }
        }*/
        public const string PATTERN = @"([^A-Fa-f0-9]|\s+?)+";

        public bool CheckStringChineseUn(string text)
        {
            bool res = false;
            foreach (char t in text)
            {
                if (t >= 0x4E00 && t <= 0x952F)
                {
                    res = true;
                    break;
                }
            }
            return res;
        }

        //是否打开16进制  是就提示只能以16进制的格式输入
        private void richTextBoxEx2_TextChanged(object sender, EventArgs e)
        {
            string msg = "";
            bool checkBoxX_16 = this.checkBoxX_16.Checked;
            if (checkBoxX_16 == true)
            {
                string rich = richTextBoxEx2.Text;
                if (rich != null)
                {                                   
                    bool bo = CheckStringChineseUn(richTextBoxEx2.Text);                  
                   if (bo)
                    {
                        MessageBox.Show("请输入正确的格式0-9 a-f A-F例如01 0d 0a");
                        richTextBoxEx2.Text = txt;
                    }
                }
            }
        }
       
        private void richTextBoxEx1_TextChanged(object sender, EventArgs e)
        {
            // AutoMsgForm auto = new AutoMsgForm(models);

            /*  AutoMsgForm auto = new AutoMsgForm(models);
              //自动回复信息
              string ric = this.richTextBoxEx1.Text;

              models = auto.GetModels();
              Task.Factory.StartNew(()=>{
                auto.autoresponse(ric,this);
              });*/
            richTextBoxEx1.Focus();//进度条往下动
        }
    }
}
